package com.zhaoguang.car.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 缓存管理
 */
@Component
public class CacheManager {

    @Autowired
    final private StringRedisTemplate stringRedisTemplate;

    //初始化
    public CacheManager(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    /**
     * 向redis中设置键值对
     */
    public boolean set(String key, String value) {
        boolean result = false;
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 向redis中设置键值对，同时设置过期时间
     */
    public boolean set(String key, String value, long time) {
        boolean result = false;
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            stringRedisTemplate.expire(key, time, TimeUnit.DAYS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取redis中的值
     */
    public String get(String key) {
        String result = null;
        try {
            result = stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 设置key的过期时间
     */
    public boolean expire(String key, long time) {
        boolean result = false;
        try {
            if (time > 0) {
                stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据key删除对应value
     */
    public boolean remove(String key) {
        boolean result = false;
        try {
            stringRedisTemplate.delete(key);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
